import os
import subprocess
import shutil
cmd = r'"G:\Program Files (x86)\FormatFactory\ffmpeg.exe" -i video.m4s -i audio.m4s -codec copy Output.mp4'
##！！！！！！！！！！！！！"G:\Program Files (x86)\FormatFactory\ffmpeg.exe"替换为你的ffmpeg安装路径
wkfolder = []

# 使用 for 循环赋值
def searchav(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith("audio.m4s"):
                folder_path = os.path.abspath(root)
                print("找到文件: {} 在文件夹: {}".format(file, folder_path))
                wkfolder.append(folder_path)
def thenoutput(folders):
    for folder_path in wkfolder:
        output_path = os.path.join(folder_path, "Output.mp4")
        if not os.path.exists(output_path):
            result = subprocess.run(cmd, shell=True, cwd=folder_path, capture_output=True, text=True)
            if result.returncode == 0:
                print("命令执行成功！")
                print("命令输出：")
                print(result.stdout)
            else:
                print("命令执行失败！")
                print("错误信息：")
                print(result.stderr)
def mvout(path):
    for folder_path in wkfolder:
    #             # 提取倒数第二个文件夹名称
                lastFoldername = os.path.basename(os.path.dirname(folder_path))
                infile=os.path.join(folder_path,"Output.mp4")
                # 构建目标文件的新路径
                print("in文件夹: {}".format(infile))
                outfile=os.path.join(current_folder,lastFoldername+".mp4")
                print("out文件夹: {}".format(outfile))
                # 移动文件到目标文件夹并重命名
                shutil.move(infile,outfile)


current_folder = os.getcwd()  # 获取当前文件夹路径
searchav(current_folder)
thenoutput(wkfolder)
mvout(current_folder)